package com.my.zl.console.service.online.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import javax.sql.DataSource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.my.zl.common.dto.ReqDTO;
import com.my.zl.common.dto.advancedQuery.PageQueryDTO;
import com.my.zl.common.enums.resp.GlobalEnum;
import com.my.zl.common.exception.BizException;
import com.my.zl.console.common.config.mybatis.MapString;
import com.my.zl.console.common.constant.AutocodeConfigC;
import com.my.zl.console.dao.online.OnlineSqlMapper;
import com.my.zl.console.dto.online.ReqSqlQueryDTO;
import com.my.zl.console.dto.online.ResSqlQueryDTO;
import com.my.zl.console.entity.autocode.ZlProject;
import com.my.zl.console.service.base.BaseManager;
import com.my.zl.console.service.online.IOnlineSqlService;

import cn.hutool.db.ds.simple.SimpleDataSource;

/**
 * 在线SQL
 * @author ZL
 */
@Service
public class OnlineSqlServiceManager extends BaseManager implements IOnlineSqlService {

    private static Logger LOGGER = LoggerFactory.getLogger(OnlineSqlServiceManager.class);
    
    private static Map<String,DataSource> dsmap = new ConcurrentHashMap<>();
    
    @Autowired
    private OnlineSqlMapper onlineSqlMapper;
    @Autowired
    protected DataSource dynamicDataSource;
    
    @Override
    public ResSqlQueryDTO querySqlResult(ReqDTO<ReqSqlQueryDTO> reqInfo,ZlProject projectInfo) throws Exception{
        // TODO Auto-generated method stub
        ReqSqlQueryDTO reqData = reqInfo.getReqData();
        ResSqlQueryDTO resDTO = new ResSqlQueryDTO();
        
        Map<String,Object> params = new HashMap<>();
        
        PageQueryDTO page = new PageQueryDTO();
        page.setLimit(reqData.getLimit());
        page.setPage(reqData.getPage());
        pageHandle(page);//处理分页数据
        
        String cdskey = AutocodeConfigC.DDS_KEY + reqData.getProjectId().toString();
        try{
            if(StringUtils.isNotBlank(projectInfo.getJdbcUrl()) && StringUtils.isNotBlank(projectInfo.getJdbcLoginname())
                    && StringUtils.isNotBlank(projectInfo.getJdbcPassword())){
                DynamicRoutingDataSource dynamicRoutingDataSource = (DynamicRoutingDataSource)dynamicDataSource;
                if(!dynamicRoutingDataSource.getCurrentDataSources().containsKey(cdskey)){
                    SimpleDataSource dynamicDataSourceVO = new SimpleDataSource(projectInfo.getJdbcUrl(), projectInfo.getJdbcLoginname(), projectInfo.getJdbcPassword());
                    dynamicRoutingDataSource.addDataSource(cdskey, dynamicDataSourceVO);
                }
                DynamicDataSourceContextHolder.push(cdskey);
            }
        }catch(Exception e){
            LOGGER.error("数据库连接异常{}",e);
            throw new BizException(GlobalEnum.DATABASE_CONNECT_FAILED);
        }
        
        try{
            Page<Object> pageHp = PageHelper.startPage(page.getPage(), page.getLimit());
            List<MapString<String, Object>> result = onlineSqlMapper.selectResultByDiySql(reqData.getSqlStr());
            
            List<MapString<String, Object>> list =  new ArrayList<>();
            List<String> fields = new ArrayList<>();
            if(result!=null && result.size()>0){
                for(Entry<String, Object> x:result.get(0).entrySet()){
                    fields.add(x.getKey());
                }
                list = result;
            }
            
            resDTO.setList(list);
            resDTO.setTotal(pageHp.getTotal());
            resDTO.setFields(fields);
        }catch(Exception e){
            LOGGER.error("数据库查询异常{}",e);
            throw new BizException(GlobalEnum.ERROR.getMsg(),e.getMessage());
        }finally {
            DynamicDataSourceContextHolder.clear();
        }
        
        return resDTO;
    }
}